import { login, logout, getInfo, loadMenu } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { userAcct, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userAcct: userAcct.trim(), password: password }).then(response => {
        console.log('login', response)
        const { data } = response
        if (data.success) {
          console.log('data.result.token = ', data.result.token)
          commit('SET_TOKEN', data.result.token)
          setToken(data.result.token)
          resolve()
        }
        reject(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { userInfo } = data
        if (!userInfo) {
          return reject('user info failed, please Login again.')
        }
        console.log('userInfo->', userInfo)
        commit('SET_NAME', userInfo.userName)
        commit('SET_AVATAR', userInfo.userAcct)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  getmenu({ commit }, parmse) {
    return new Promise((resolve, reject) => {
      loadMenu().then(response => {
        // // console.log(response)
        const menu = response.result.data
        const getMenuList = (menu) => {
          if (!menu || !menu.length) { return }
          const res = []
          const tmpMap = []
          for (let i = 0; i < menu.length; i++) {
            tmpMap[menu[i].id] = menu[i]
            menu[i].component = menu[i].url
            menu[i].path = menu[i].url
            const name = menu[i].url.split('/')
            if (name.length === 2) {
              menu[i].name = name[1].charAt(0).toUpperCase() + name[1].slice(1)
            } else if (name.length === 3 || name.length === 4) {
              menu[i].name = name[2].charAt(0).toUpperCase() + name[2].slice(1)
            }
            menu[i].meta = { 'icon': menu[i].iconCls, 'title': menu[i].text }
            delete menu[i].leaf
            if (tmpMap[menu[i].pid] && menu[i].id !== menu[i].pid) {
              if (!tmpMap[menu[i].pid].children) {
                tmpMap[menu[i].pid].children = []
              }
              tmpMap[menu[i].pid].children.push(menu[i])
            } else {
              res.push(menu[i])
            }
          }
          return res
        }
        const menuLists = getMenuList(menu)
        localStorage.setItem('menuList', JSON.stringify(menuLists))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

